package middlewares

import (
	"fmt"
	"net/http"
	"strings"
	"sync"
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/patrickmn/go-cache"
)

// 初始化缓存
var (
	once      sync.Once
	cacheCode *cache.Cache
)

// 需要同构once来实现只有首次加载初始化，防止多次实例化缓存函数
func InitCache() *cache.Cache {
	once.Do(func() {
		cacheCode = cache.New(5*time.Minute, 10*time.Minute)
	})

	return cacheCode
}

// , "/chat/chat/index"
func InitMiddleware(c *gin.Context) {
	//设置全局缓存
	cacheCode := InitCache()
	// 将缓存存储在上下文中
	c.Set("CacheCode", cacheCode)
	// 设置 JSON 格式的 Content-Type
	c.Header("Content-Type", "application/json")
	// 设置需要的白名单
	whitelist := []string{"/api/login/index", "/api/login/signup", "/api/login/code", "/api/login/demo", "/api/login/verify", "/api/demo/index", "/api/demo/demo"}
	fmt.Println("当前地址", c.Request.URL.Path)
	// 检查请求的路径是否在白名单中
	for _, path := range whitelist {
		if path == c.Request.URL.Path {
			c.Next()
			return
		}
	}

	// 从请求的Header中获取JWT令牌
	tokenString := c.GetHeader("Authorization")

	fmt.Println("抓取令牌信息", tokenString)

	if tokenString == "" {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
		c.Abort()
		return
	}

	// 解析JWT令牌
	token, err := jwt.Parse(strings.TrimPrefix(tokenString, "Bearer "), func(token *jwt.Token) (interface{}, error) {
		// 这里可以添加自定义的逻辑来获取密钥
		return []byte("qinuoyun"), nil
	})

	if err != nil || !token.Valid {
		c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
		c.Abort()
		return
	}

	// 在上下文中设置用户身份信息
	claims, _ := token.Claims.(jwt.MapClaims)

	fmt.Println("claims", claims)
	c.Set("userId", claims["userId"])
	c.Set("mobile", claims["mobile"])

	c.Next()
}
